<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\LakalaModel;
use think\Db;
use think\Log;

class Lakala extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * 拉卡拉支付回调
     * @return \think\response\Json
     */
    public function lakalNotify(){
        $returnData = [
            "code" => "SUCCESS",
            "message" => "执行成功"
        ];
        $response = file_get_contents("php://input");
        Log::record('拉卡拉回调参数', $response);
        $lakala = new LakalaModel();
        if($response) {
            //签名验证通过
            $result = json_decode($response, 1);
            if($result){
                $search=$lakala->search($result['out_order_no']);
                if (!$search){
                    return json([
                        "code" => "ERROR",
                        "message" => "未支付"
                    ]);
                }
                Db::startTrans();
                try{
                    $params = request()->param();
                    //修改数据
                    $up = Db::name('list_one')
                        ->where(['id'=>$params['id']])
                        ->update([
                            'jiaofei'=>2,
                            'jiaofei_price'=>$result['total_amount']/100,
                            'trade_no'=>$result['pay_order_no'],
                            'out_trade_no'=>$result['out_order_no'],
                            'jiaofei_time'=>date("Y-m-d H:i:s",time()),
                            'jiaofei_type'=>1,
                            'qianzi_status'=>5,
                            'type'=>$params['type']
                        ]);
                    $channel_id = $params['channel_id'];
                    $model = new Index();
                    $model->num($params['id'],$channel_id);
                    // 提交事务
                    Db::commit();
                    db('ceshi')->insert(['text'=>$params['id'].'|'.date("Y-m-d H:i:s",time()).'|'.$result['out_order_no'].'|']);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $c = $e->getMessage();
                    db('ceshi')->insert(['text'=>'111'.date("Y-m-d H:i:s",time()).$c]);
                    $returnData = [
                        "code" => "ERROR",
                        "message" => "回调失败"
                    ];
                }
            }else{
                $returnData = [
                    "code" => "ERROR",
                    "message" => "回调失败"
                ];
            }
            Log::record('STEP', '验签通过');
        } else {
            //签名不通过
            $returnData = [
                "code" => "ERROR",
                "message" => "签名不通过"
            ];
        }
        return json($returnData);
    }

}